package com.dm.cloud.service.impl;

import com.alibaba.nacos.common.utils.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.dm.cloud.api.dto.ChatCache;
import com.dm.cloud.api.dto.Users;
import com.dm.cloud.api.service.IChatOnlineService;
import com.dm.cloud.api.vo.ChatMessageVo;
import com.dm.cloud.common.CloudConstant;
import com.dm.cloud.common.R;
import com.dm.cloud.dao.ChatCacheDao;
import com.dm.cloud.feign.auth.AuthFeign;
import com.dm.cloud.utils.EntityUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;

/**

 */
@Slf4j
@Service
public class ChatOnlineServiceImpl implements IChatOnlineService {

    @Autowired
    ChatCacheDao chatCacheDao;

    @Autowired
    AuthFeign authFeign;

    @Override
    public List<Object> getUsersList() {
        List<Users> users = authFeign.getUserList().getResult();
        List<Object> result =new ArrayList<>();
        if(CollectionUtils.isNotEmpty(users)){
            for (Users user : users) {
                if(user.getId() != getCurrentUser().getId()) {
                    Users us = new Users();
                    us.setId(user.getId());
                    us.setRealName(Optional.ofNullable(user.getRealName()).orElse(user.getUserName()));
                    Object resInner = EntityUtils.removeNullField(us);
                    result.add(resInner);
                }
            }
        }
        return result;
    }

    @Override
    public List<ChatMessageVo> searchCache(String id, String datetime) {
        //查看时间节点是不是正常的
        Date date = null;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-DD HH:mm:ss");

        try {
            date = sdf.parse(datetime);
        } catch (Exception e) {
            log.error("时间条件格式错误");
        }

        Users sender = getCurrentUser();
        QueryWrapper<ChatCache> queryWrapper = new QueryWrapper<>();
        if(id.startsWith("group_")){
            //群组的对话记录查询
            //直接查询接受人是群组id的
            queryWrapper.eq("receiver_id",id);
        }else {
            //用户对用户的对话记录查询
            //查询我发给他的 和 他发给我的
            queryWrapper.and(e -> e.eq("sender_id", sender.getId()).eq("receiver_id", id))
                    .or(in -> in.eq("sender_id", id).eq("receiver_id", sender.getId()));
        }
        //前端没有传回时间节点的话就查询最近一周的数据
        if (ObjectUtils.isEmpty(date)){
            //查询最近三天的消息
            LocalDateTime dateTime = LocalDateTime.now();
            dateTime = dateTime.plusDays(-7);
            datetime = dateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:MM:ss"));
        }

        //从指定时间节点向后查询
        queryWrapper.gt("send_time",datetime);
        queryWrapper.orderByAsc("send_time");

        List<ChatCache> cacheList = chatCacheDao.selectList(queryWrapper);

        List<ChatMessageVo> msgList = new ArrayList<>();

        if(CollectionUtils.isNotEmpty(cacheList)){
            for (ChatCache chatCache : cacheList) {
                ChatMessageVo msgInner = new ChatMessageVo();
                msgInner.setSenderId(String.valueOf(chatCache.getSenderId()));
                msgInner.setReceiverId(chatCache.getReceiverId());
                msgInner.setContentType(chatCache.getContentType());
                msgInner.setMessage(chatCache.getMessageContent());
                msgInner.setSendTime(chatCache.getSendTime());
                msgList.add(msgInner);
            }
        }

        return msgList;

    }

    /**
     * 获取当前用户后的操作
     * @param consumer
     */
    private Users getCurrentUser(){
        //调用auth服务
        R<Users> user = authFeign.getCurrentUser(CloudConstant.AUTH_REQUEST_UUID);
        if("success".equals(user.getType())
                && CloudConstant.RESPONSE_SUCCESS_CODE == user.getCode()
                && Optional.ofNullable(user.getResult()).isPresent()) {
            Users userDto = user.getResult();
            return userDto;
        }else{
            throw new RuntimeException("用户信息获取失败，请重新登陆尝试");
        }
    }
}